#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"../include/vfs.h"


void hash_table()
{
	int i;
	for(i=0;i<27;i++)
	{
	
		roots.hashtable[i]=(np)malloc(sizeof(node));
		roots.hashtable[i]->next=NULL;
		roots.hashtable[i]->fdes=NULL;
	}
}



int hashing(int x)
{
	if(x>=65 && x<=91)
          return x%65;
        else if(x>=97 && x<=122)
          return x%97;
	else
	  return 26;
}


int hash_insertion(FD *fdesc,int index)
{
	np newnode;
	newnode=(np)malloc(sizeof(node));
	
	newnode->fdes=malloc(sizeof(FD));
	
	strcpy(newnode->fdes->filename,fdesc->filename);
	strcpy(newnode->fdes->path,fdesc->path);
	newnode->fdes->file_type=fdesc->file_type;
	newnode->fdes->file_size=fdesc->file_size;
	newnode->fdes->block_no=fdesc->block_no;

	newnode->next=NULL;   

	if(index<27)
 	{
		if(roots.hashtable[index]->next==NULL)
		{
			roots.hashtable[index]->next=newnode;
		}
		else
		{     
			newnode->next=roots.hashtable[index]->next;
                	roots.hashtable[index]->next=newnode;		
		}
	  	 return index;
	}
	else
		return -1;

}



void hashtable_insert(FD *fd)
{

	char fchar;
	char name[50];
	int position,index;
	
	fchar=fd->filename[0];
	index=hashing(fchar);


	if(index==-1)
	{
		//printf("\nInvalid file name \n");
	}

	else
		{
			position=hash_insertion(fd,index);
	
  		} 

}


np hash_search(char name[])
{
	
	int loc,position,index;
	np temp;
	char fchar;
	
	fchar=name[0];
	index=hashing(fchar);
	
	temp = roots.hashtable[index];
		
		if(temp!=NULL && temp->next!=NULL)
		{
			temp=temp->next;	
				
			/*while(temp!=NULL)
			{
				if(strcmp(temp->fdes->filename,name)==0)
				{
					return temp;
				}
				
				temp=temp->next;
			}
			*/

			return temp;
		}
	return (np)NULL;
	
}

/*
void hash_traversal()
{ 	np temp;
	int i=0;
	for(i=0;i<26;i++)
	{
		printf("\n %d", i);		
		temp=roots.hashtable[i];
		if(temp!=NULL)
		{	temp=temp->next;
			while(temp!=NULL)
			{
			printf(" \t%s \t", temp->fdes->filename);
			temp=temp->next;
			}
		}
	}
}

*/


int hash_deletion(FD *fd)
{

	char fchar;
	int position,index=0;
	
	np temp,tmp;

	
	while(index<27)
	{
		temp=roots.hashtable[index];

		tmp=temp;
		
		while(temp!=NULL && temp->next!=NULL)
		{	
			
			temp = temp->next;

			if(strcmp(temp->fdes->path,fd->path)==0 || strstr(temp->fdes->path,fd->path)!=NULL)
			{
				tmp->next = temp->next;
			
			}

			else
				tmp=temp;
		}	
		
		index++;		
	}

}	







